package com.zhang.common.core.util;

import lombok.experimental.UtilityClass;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @Description
 * @Author zsw
 * @Date 2019/11/20 10:29
 * @Version V1.0
 **/
@UtilityClass
public class EntityUtil {

    private Date now = new Date();

    public static <T> void setCreatAndUpdatInfo(T entity) {

        setCreateInfo(entity);
        setUpdatedInfo(entity);
    }

    public static <T> void setUpdatedInfo(T entity) {
        String[] fields = {"updateTime","updateUser","updateHost"};
        setInfo(entity,fields,now);
    }


    private static <T> void setCreateInfo(T entity) {
        String[] fields = {"createTime","createUser","createHost"};
        setInfo(entity,fields,now);
    }

    private static <T> void setInfo(T entity,String[] fields,Date now) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        Object [] value =  new Object []{now,UserUtil.getUsername(),WebUtils.getIP(request)};

        value =  new Object []{now,"tseter","1.1.1.1"};
        // 填充默认属性值
        setDefaultValues(entity, fields, value);

    }


    private static <T> void setDefaultValues(T entity, String[] fields, Object[] value) {
        for(int i=0;i<fields.length;i++){
            String field = fields[i];
            if(ReflectionUtils.hasField(entity, field)){
                ReflectionUtils.invokeSetter(entity, field, value[i]);
            }
        }
    }

}